<template>
  <div class="img">
    <a-upload
      name="file"
      listType="picture-card"
      :multiple="isMultiple"
      :action="uploadAction"
      :headers="headers"
      :data="{ biz: bizPath }"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      :disabled="disabled"
      :isMultiple="isMultiple"
      @change="handleChange"
      @preview="handlePreview"
      :class="[
        !isMultiple ? 'imgupload' : '',
        !isMultiple && picUrl ? 'image-upload-single-over' : '',
      ]"
    >
      <div>
        <div class="iconp">
          <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
          <div class="ant-upload-text">{{ text }}</div>
        </div>
      </div>
      <a-modal
        ok-text="确认"
        cancel-text="取消"
        :maskClosable="false"
        :visible="previewVisible"
        :destroyOnClose="true"
        :footer="null"
        @cancel="handleCancel()"
      >
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-upload>
  </div>
</template>

<script>
import { apiUrl } from "@/api/URLConfig";
import ImageCompressor from "js-image-compressor";
const uidGenerator = () => {
  return "-" + parseInt(Math.random() * 10000 + 1, 10);
};
const getFileName = (path) => {
  if (path.lastIndexOf("\\") >= 0) {
    let reg = new RegExp("\\\\", "g");
    path = path.replace(reg, "/");
  }
  return path.substring(path.lastIndexOf("/") + 1);
};
export default {
  name: "JImageUpload",
  data() {
    return {
      uploadAction: apiUrl + "/fileLocal/uploads",
      uploadLoading: false,
      picUrl: false,
      headers: {},
      fileList: [],
      previewImage: "",
      previewVisible: false,
    };
  },
  props: {
    text: {
      type: String,
      required: false,
      default: "上传",
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: "temp",
    },
    value: {
      type: [String, Array],
      required: false,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false,
    },
    number: {
      type: Number,
      required: false,
      default: 0,
    },
  },
  watch: {
    value: {
      handler(val, oldValue) {
        if (val instanceof Array) {
          this.initFileList(val.join(","));
        } else {
          this.initFileList(val);
        }
        if (!val || val.length == 0) {
          this.picUrl = false;
        }
      },
      //立刻执行handler
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    initFileList(paths) {
      if (!paths || paths.length == 0) {
        this.fileList = [];
        return;
      }
      this.picUrl = true;
      let fileList = [];
      let arr = paths.split(",");
      for (var a = 0; a < arr.length; a++) {
        let url = arr[a];
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: "done",
          url: `${apiUrl}${url}`,
          response: {
            status: "history",
            message: arr[a],
          },
        });
      }
      this.fileList = fileList;
    },
    beforeUpload(file) {
      this.compressionImage(file);
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("只能上传jpg,png!");
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error("文件最大20MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    compressionImage(file) {
      return new Promise((resolve, reject) => {
        // eslint-disable-next-line no-new
        new ImageCompressor({
          file: file,
          quality: 0.8,
          maxWidth: 1500,
          maxHeight: 1500,
          redressOrientation: false,

          // 压缩前回调
          beforeCompress: function(result) {
            console.log("压缩之前图片尺寸大小: ", result.size);
            console.log("mime 类型: ", result.type);
          },

          success: function(result) {
            console.log("压缩之后图片尺寸大小: ", result.size);
            console.log("mime 类型: ", result.type);
            console.log(
              "实际压缩率： ",
              (((file.size - result.size) / file.size) * 100).toFixed(2) + "%"
            );
            resolve(result);
          },
          error(e) {
            reject(e);
          },
        });
      });
    },
    handleChange(info) {
      this.picUrl = false;
      let fileList = info.fileList;
      if (this.number > 0 && this.isMultiple) {
        fileList = fileList.slice(-this.number);
      }
      if (info.file.status === "done") {
        if (info.file.response.code == 200) {
          this.picUrl = true;
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.data;
            }
            return file;
          });
        }
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
      } else if (info.file.status === "removed") {
        const that = this;
        this.$confirm({
          title: "提示",
          content: "该操作会永久删除该图片？",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            that.handlePathChange();
          },
          onCancel() {},
        });
        return;
      }
      this.fileList = fileList;
      if (info.file.status === "done" || info.file.status === "removed") {
        this.handlePathChange();
      }
    },
    // 预览
    handlePreview(file) {
      this.previewImage = `${apiUrl}${file.url}` || `${apiUrl}${file.thumbUrl}`;
      console.log(this.previewImage, "9090909");
      this.previewVisible = true;
    },
    handlePathChange() {
      let uploadFiles = this.fileList;
      let path = "";
      if (!uploadFiles || uploadFiles.length == 0) {
        path = "";
      }
      let arr = [];
      if (!this.isMultiple && uploadFiles.length > 0) {
        arr.push(uploadFiles[uploadFiles.length - 1].response.data);
      } else {
        for (let a = 0; a < uploadFiles.length; a++) {
          let uploadFilesUrl = uploadFiles[a];
          if (
            uploadFiles[a].status === "done" &&
            uploadFilesUrl.response &&
            uploadFilesUrl.response.data
          ) {
            arr.push(uploadFilesUrl.response.data);
          } else if (
            uploadFiles[a].status === "done" &&
            uploadFilesUrl.response &&
            uploadFilesUrl.response.message
          ) {
            arr.push(uploadFilesUrl.response.message);
          } else {
            return;
          }
        }
      }
      if (arr.length > 0) {
        path = arr.join(",");
      }
      console.log(path, arr);
      this.$emit("change", path);
    },
    handleDelete(file) {
      this.fileList = [];
      //如有需要新增 删除逻辑
      console.log(file);
    },
    handleCancel() {
      this.close();
      this.previewVisible = false;
    },
    close() {},
  },
  model: {
    prop: "value",
    event: "change",
  },
};
</script>

<style scoped lang="less">
/deep/ .imgupload .iconp {
  padding: 20px;
}
/deep/ .image-upload-single-over .ant-upload-select {
  display: none;
}
</style>
